package com.oocl.ha.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import com.oocl.ha.dao.MerchantDao;
import com.oocl.ha.entity.Merchant;

@Repository("merchantDao")

public class MerchantDaoImpl implements MerchantDao {

	@PersistenceContext(name = "un")
	private EntityManager em;

	public Merchant merchantLogin(String account, String password) {
		Merchant m = null;
		try {
			m = (Merchant) em
					.createQuery(
							"select merchant from Merchant merchant where merchant.account =:account and merchant.password=:password")
					.setParameter("account", account).setParameter("password", password).getSingleResult();
			if (m == null) {
				return null;
			}
		} catch (Exception e) {
			System.out.println("No account be found.");
			return null;
		}
		return m;
	}

	public int merchantRegister(Merchant merchant) {
		try {
			em.persist(merchant);
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		return 1;
	}

	public boolean merchantIsRegist(String account) {
		try {
			String sql = "select merchant from Merchant merchant where merchant.account =:account";
			Merchant merchants = (Merchant) em.createQuery(sql).setParameter("account", account).getSingleResult();
			if (merchants != null) {
				return true;
			}
		} catch (Exception re) {
			System.out.println("The current account is not existed.");
			return false;
		}
		return false;
	}

	public List<Merchant> findActiveMerchant() {
		try {
			final String sql = "select merchant from Merchant merchant where merchant.statue = 1";
			@SuppressWarnings("unchecked")
			List<Merchant> merchants = em.createQuery(sql).getResultList();
			return merchants;
		} catch (RuntimeException re) {
			re.printStackTrace();
		}
		return null;
	}

	public Merchant findById(int mid) {
		Merchant merchant = em.find(Merchant.class, mid);
		return merchant;
	}

}
